package com.xq.config;

import com.xq.io.Resource;
import com.xq.pojo.Configuration;
import com.xq.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.SAXException;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: xiaoqiang
 * @Description:
 * @Date: 2021/5/29
 * @Version: 1.0
 */
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * @param path
     */
    public void parse(String path) throws SAXException, DocumentException {
        HashMap<String, MappedStatement> map = new HashMap<>();
        InputStream in = Resource.getResource(path);
        Document read = new SAXReader().read(in);
        Element rootElement = read.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        List<Element> list = rootElement.selectNodes("//select");
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramType = element.attributeValue("paramType");
            //获取sql
            String textSql = element.getTextTrim();


            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParamterType(paramType);
            mappedStatement.setSql(textSql);
            map.put(namespace + "." + id, mappedStatement);
        }
        configuration.setSql(map);
    }
}
